import { StoreOptions } from 'vuex'
import http from '@/http';

interface IAuthState {
    isLogined: boolean,
    token: string,
    username: string
}

export const moduleAuth: StoreOptions<IAuthState> = {
    state: {
        isLogined: false,
        token: "",
        username: ""
    },
    mutations: {
        login(state, playload: { token: string, username: string }) {
            state.token = playload.token
            localStorage.setItem('token', playload.token)
            state.username = playload.username
            state.isLogined = true
        },
        logout(state) {
            state.isLogined = false
            state.token = ""
            state.username = ""
            localStorage.removeItem('token')
        }
    },
    actions: {
        async loginAsync({ commit }, playload: { name: string, password: string }) {
            let response = await http.post('/api/auth/login', {
                name: playload.name,
                password: playload.password
            })
            if (response.data.length > 0) {
                commit('login', { token: response.data, username: playload.name })
            }
        },
        async checkLoginAsync({ commit }) {
            let token = localStorage.getItem('token')
            if (token != null) {
                commit('login', { token: token, username: 'admin' })

                let response = await http.get('/api/auth/check-login')
                // console.log(response)
                if (response.data != "") {
                    commit('login', { token: token, username: response.data })
                } else {
                    commit('logout')
                }
            }
        },
        changePasswordPromise({ commit }, playload: { password: string, newPassword: string, reNewPassword: string }) {
            return http.put('/api/auth/change-password', {
                password: playload.password,
                new_password: playload.newPassword,
                re_new_password: playload.reNewPassword
            })
        }
    }
}